﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using ChinaDynastyTours.Assets;
using ChinaDynastyTours.Assets.DataSet;
using ChinaDynastyTours.Controls;
using ChinaDynastyTours.Helpers;
using ChinaDynastyTours.Models;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using System.IO;

namespace ChinaDynastyTours.Views
{
    public partial class PayApplyForm : DevExpress.XtraEditors.XtraForm
    {
        private DataTable _dtPayApply;
        private bool m_checkStatus = false;

        public PayApplyForm()
        {
            InitializeComponent();

            //默认为上3月1日起，下下月1日止
            dateStart.EditValue = DateTime.Parse(string.Format("{0}-{1}-01", DateTime.Now.Month > 3 ? DateTime.Now.Year : DateTime.Now.Year - 1, DateTime.Now.Month > 3 ? DateTime.Now.Month - 3 : DateTime.Now.Month + 9));
            dateEnd.EditValue = DateTime.Parse(string.Format("{0}-{1}-01", DateTime.Now.Year + DateTime.Now.Month / 11, (DateTime.Now.Month + 1) % 12 + 1));


            //初始化团下拉列表
            DataSet ds = TeamGroupCtrl.GetAllIDForTeamGroup();
            if (ds.Tables.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                    btnTeamGroupID.Properties.Items.Add(dr["TourGroupID"].ToString().Trim());
            }

            tbPlanPayTime.DateTime = DateTime.Now;
        }

        //private void btnProviders_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        //{
        //    ProviderSelectedToolForm providerServiceForm = new ProviderSelectedToolForm()
        //    {
        //        _ProviderTypes = new ProviderTypeEnum[] {
        //        ProviderTypeEnum.宾馆,ProviderTypeEnum.餐厅,ProviderTypeEnum.旅行社,ProviderTypeEnum.汽车,ProviderTypeEnum.演出,
        //        ProviderTypeEnum.景点,ProviderTypeEnum.火车票,ProviderTypeEnum.飞机票 },
        //    };

        //    if (providerServiceForm.ShowDialog(this) == DialogResult.OK)
        //    {
        //        DevExpress.XtraEditors.ButtonEdit btnEdit = sender as DevExpress.XtraEditors.ButtonEdit;
        //        btnEdit.Tag = providerServiceForm.ReturnProviderID;
        //        btnEdit.EditValue = providerServiceForm.ReturnProviderName;
        //    }
        //}

        private void btnProviders_Properties_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Close)
            {
                DevExpress.XtraEditors.ButtonEdit btnEdit = sender as DevExpress.XtraEditors.ButtonEdit;
                btnEdit.Tag = null;
                btnEdit.EditValue = null;
            }
            else
            {
                ProviderSelectedToolForm providerServiceForm = new ProviderSelectedToolForm()
                {
                    _ProviderTypes = new ProviderTypeEnum[] {
                ProviderTypeEnum.宾馆,ProviderTypeEnum.餐厅,ProviderTypeEnum.旅行社,ProviderTypeEnum.汽车,ProviderTypeEnum.演出,
                ProviderTypeEnum.景点,ProviderTypeEnum.火车票,ProviderTypeEnum.飞机票 },
                };

                if (providerServiceForm.ShowDialog(this) == DialogResult.OK)
                {
                    DevExpress.XtraEditors.ButtonEdit btnEdit = sender as DevExpress.XtraEditors.ButtonEdit;
                    btnEdit.Tag = providerServiceForm.ReturnProviderID;
                    btnEdit.EditValue = providerServiceForm.ReturnProviderName;
                }
 
            }
        }
        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            string providerId = btnProviders.Tag == null ? "" : btnProviders.Tag.ToString();

            ProviderTypeEnum[] providerTypes = new ProviderTypeEnum[] { ProviderTypeEnum.宾馆, ProviderTypeEnum.旅行社, ProviderTypeEnum.火车票, ProviderTypeEnum.飞机票, ProviderTypeEnum.其它 };

            _dtPayApply = ExpensesCtrl.GetExpenseDataforApply(btnTeamGroupID.Text, providerId, providerTypes, dateStart.DateTime, dateEnd.DateTime, btnPayStatus.Text);
            expenseGridViewControl.DataSource = AddGridSelectedColumn(_dtPayApply);
        }
        /// <summary>
        /// 添加‘选择’附加列
        /// </summary>
        /// <param name="dtSource"></param>
        /// <returns></returns>
        private DataTable AddGridSelectedColumn(DataTable dtSource)
        {
            dtSource.Columns.Add("Selected", typeof(bool));
            return dtSource;
        }

        #region 行数据校验

        private void expenseGridView_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            //DataRowView dr = e.Row as DataRowView;
            //decimal applyPay = decimal.Parse(dr["ApplyPay"].ToString());//本次申请额
            //decimal applyPayTotal = decimal.Parse(dr["ApplyPayTotal"].ToString());//已申请总额
            //decimal budget = decimal.Parse(dr["Budget"].ToString());//已申请总额
            //if (applyPay + applyPayTotal > budget)
            //{
            //    expenseGridView.SetColumnError(expenseGridView.Columns["ApplyPay"], "'已申请总额'与'本次申请额'和超出'预算价'", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Default);
            //    e.Valid = false;
            //}
        }

        private void expenseGridView_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            //if (e.RowHandle >= 0)
            //{
            //    DataRowView dr = e.Row as DataRowView;
            //    decimal applyPay = decimal.Parse(dr["ApplyPay"].ToString());//本次申请额
            //    decimal applyPayTotal = decimal.Parse(dr["ApplyPayTotal"].ToString());//已申请总额
            //    decimal budget = decimal.Parse(dr["Budget"].ToString());//已申请总额
            //    if (applyPay + applyPayTotal > budget)
            //        e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
            //}
        }
        #endregion

        #region 打钩选择
        /// <summary>
        /// 选择框多选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelectedCheckEdit_CheckedChanged(object sender, EventArgs e)
        {

            #region 打钩选择行

            int iFocuse = expenseGridView.FocusedRowHandle;

            //是否已经提交过报销检测
            string payStatus = expenseGridView.GetRowCellValue(iFocuse, "PayStatus").ToString();
            if (payStatus == PayApplyStatusEnum.付清.ToString())
            {
                CheckEdit checkEdit = (sender as CheckEdit);
                if (checkEdit.Checked == true)
                {
                    checkEdit.Checked = false;
                    MessageBox.Show("此项费用已经‘付清’，不能再申请！");
                    return;
                }
            }

            //expenseGridView.ClearSelection();

            //if ((sender as CheckEdit).Checked)
            //    expenseGridView.SelectRow(iFocuse);

            //int[] rowIds = MutilRow(expenseGridView);

            #endregion

        }

        private int[] MutilRow(GridView gv)
        {
            List<int> rowIds = new List<int>();
            for (int i = 0; i < gv.RowCount; i++)
            {
                object objValue = gv.GetRowCellValue(i, "Selected");
                if (objValue != null)
                {
                    bool check = false;
                    bool.TryParse(objValue.ToString(), out check);
                    if (check)
                    {
                        rowIds.Add(i);
                    }
                }
            }
            return rowIds.ToArray();
            //object selected;
            //for (int i = 0; i < gv.RowCount; i++)
            //{
            //    selected = gv.GetRowCellValue(i, "Selected");

            //    if (string.IsNullOrEmpty(selected.ToString())) continue;

            //    if (Convert.ToBoolean(selected) == true)
            //    {
            //        //payApplyGridView.focusedrow.BackColor = Color.Red;
            //        gv.SelectRow(i);
            //    }
            //}
            //return gv.GetSelectedRows();
        } 
        #endregion

        private void btnSendEMail_Click(object sender, EventArgs e)
        {
            decimal totalpayment;
            string providerID;
            int[] rowIds;

            #region 校验选择内容数据
            msg.Clear();
            rowIds = MutilRow(expenseGridView);
            if (rowIds.Length >= 1)
            {
                providerID = expenseGridView.GetRowCellValue(rowIds[0], "ProviderID").ToString();
                totalpayment = decimal.Parse(expenseGridView.GetRowCellValue(rowIds[0], "ApplyPay").ToString());
                for (int i = 0; i < rowIds.Length; i++)
                    if (providerID != expenseGridView.GetRowCellValue(rowIds[i], "ProviderID").ToString())
                    {
                        msg.AppendText("选中项的各个'供应商'不完全相同，请选择相同供应商项\r\n");
                        messageDockPanel.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Visible;
                        return;
                    }
            }
            else
            {
                msg.AppendText("没有选择任何内容，请在选择项上打‘√’\r\n");
                return;
            }
            #endregion

            //任选一项提取供应商信息
            ProviderEntity provider = BaseInfoCtrl.GetProviderDataByID(providerID);
            if (provider != null)
            {
                #region 生成付款申请单和付款申请单详情数据
                string currentUser = UserInfoCtrl.GetNameByUserName(Thread.CurrentPrincipal.Identity.Name);//当前登录者

                //PayApplyEntity payApplyEntity = new PayApplyEntity()
                //{
                //    ProviderName = provider.ProviderName,
                //    ProviderID = provider.ProviderID,
                //    TotalpaymentG = MoneyHelper.ChMoney(totalpayment),
                //    TotalpaymentL = totalpayment,
                //    Applicants = currentUser,
                //    Audit = "",
                //    PlanPayTime = "",
                //    ApplyPayTime = DateTime.Today.ToString("yyyy-MM-dd"),//申请时间
                //    PayTime = "",//财务付款时间
                //    PayStatus = PayStatusEnum.未付.ToString(),
                //    Remark = "",
                //    Voucher = ""
                //};

                #endregion

                #region 发送或预览催款申（报表）

                PayApplyFormDataSet ds = new PayApplyFormDataSet();//由于催款单报表是由付款申请单修改得来，因此数据源采用同一个
                DataTable dt = PayApplyCtrl.GetPayApplyDataById("-1");//传入‘-1’获取表结构
                DataRow dr = dt.NewRow();
                dr["PayApplyID"] = "00000000";
                //dr["ProviderName"] = provider.ProviderName;
                //dr["ProviderID"] = provider.ProviderID;
                //dr["TotalpaymentG"] = payApplyEntity.TotalpaymentG;
                //dr["TotalpaymentL"] = payApplyEntity.TotalpaymentL;
                dr["Applicants"] = currentUser;
                //dr["Audit"] = payApplyEntity.Audit;
                //dr["PlanPayTime"] = payApplyEntity.PlanPayTime;
                //dr["ApplyPayTime"] = payApplyEntity.ApplyPayTime;
                //dr["PayTime"] = payApplyEntity.PayTime;
                //dr["PayStatus"] = payApplyEntity.PayStatus;
                //dr["Remark"] = payApplyEntity.Remark;
                dt.Rows.Add(dr);

                //导入数据,三个表fin_PayApply、bas_Provider、fee_Expense
                ds.Tables["fin_PayApply"].ImportRow(dr);

                ds.Tables["bas_Provider"].Rows.Add();
                ds.Tables["bas_Provider"].Rows[0]["ProviderName"] = provider.ProviderName;
                ds.Tables["bas_Provider"].Rows[0]["FullName"] = provider.FullName;
                ds.Tables["bas_Provider"].Rows[0]["Contact"] = provider.Contact;
                ds.Tables["bas_Provider"].Rows[0]["Telephone"] = provider.Telephone;
                ds.Tables["bas_Provider"].Rows[0]["Fax"] = provider.fax;
                ds.Tables["bas_Provider"].Rows[0]["AccountBank"] = provider.AccountBank;
                ds.Tables["bas_Provider"].Rows[0]["Account"] = provider.Account;

                foreach (int id in rowIds)
                    ds.Tables["fee_Expense"].ImportRow(expenseGridView.GetDataRow(id));

                PayApplyDemandBillRpt rpt = new PayApplyDemandBillRpt(dateStart.DateTime.ToString("yyyy-MM-dd"), dateEnd.DateTime.ToString("yyyy-MM-dd"));
                rpt.DataSource = ds;
                if (sender.Equals(btnPreviewBill))
                {
                    new PrintPreviewForm(rpt, "").ShowDialog();
                    return;
                }
                string file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "demandbill_" + providerID.Trim() + ".pdf");
                rpt.ExportToPdf(file);

                List<string> files = new List<string>();
                files.Add(file);

                //发送邮件

                if (EMailHelper.SendMail(new List<string>() { provider.email }, provider.ProviderName + dateStart.DateTime.ToString("yyyy-MM") + "到" + dateEnd.DateTime.ToString("yyyy-MM") + "月结账单", provider.FullName + ",\r\n    请在收到该邮件后三日内提供账单。\r\n\r\n北京龙润国际旅行社有限公司", files, provider.ProviderName, LogTypeEnum.操作类))
                    MessageBox.Show("邮件发送成功！", "信息提示");
                else
                    MessageBox.Show("邮件发送失败，详情请查看日志", "信息提示");

                //删除附件
                foreach (string filePath in files)
                {
                    if (File.Exists(filePath))
                        File.Delete(filePath);
                }
                #endregion
            }
            //}

        }

        
        #region 打印付款申请单
        /// <summary>
        /// 打印付款申请单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrintAndPreview_Click(object sender, EventArgs e)
        {
            decimal totalpayment;
            string providerID;
            int[] rowIds;

            //校验选择内容数据
            if (!ValidateData(out totalpayment, out providerID, out rowIds))
                return;
            DialogResult dResult = sender.Equals(btnPreview) ? DialogResult.Retry : MessageBox.Show("请注意，本次打印的同时将会一并发送申请单到财务，过程不可逆，是否确认？", "打印确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (DialogResult.Yes == dResult || DialogResult.Retry == dResult)
            {
                //任选一项提取供应商信息
                ProviderEntity provider = BaseInfoCtrl.GetProviderDataByID(providerID);
                if (provider != null)
                {
                    #region 生成付款申请单和付款申请单详情数据
                    string currentUser = UserInfoCtrl.GetNameByUserName(Thread.CurrentPrincipal.Identity.Name);//当前登录者
                    string payApplyId = "00000000";
                    
                    //准备付款申请单数据
                    PayApplyEntity payApplyEntity = new PayApplyEntity()
                    {
                        //PayApplyID = ,
                        ProviderName = provider.ProviderName,
                        ProviderID = provider.ProviderID,
                        //Contact = tbContact.Text,//provider.Contact,
                        //Telephone = provider.Telephone,
                        //Fax = provider.fax,
                        TotalpaymentG = MoneyHelper.ChMoney(totalpayment),
                        TotalpaymentL = totalpayment,
                        Applicants = currentUser,
                        Audit = "",
                        PlanPayTime = provider.IsSigned == 1 ? "月结" : tbPlanPayTime.DateTime.ToString("yyyy-MM-dd"),//是月结供应商则‘月结’，否则提供拟汇款时间
                        ApplyPayTime = DateTime.Today.ToString("yyyy-MM-dd"),//申请时间
                        PayTime = "",//财务付款时间
                        PayStatus = PayStatusEnum.未付.ToString(),
                        Remark = currentUser + " 申请 " + provider.ProviderName + " 费用",
                        Voucher = ""
                    };

                    //准备付款详情数据
                    string[] providerIds = new string[rowIds.Length];
                    PayDetailEntity[] payDetailEntity = new PayDetailEntity[rowIds.Length];

                    for (int i = 0; i < rowIds.Length; i++)//为每一条数据创建一条付款详情信息——供历史查询
                    {
                        payDetailEntity[i] = new PayDetailEntity();
                        //entity[i].PayApplyID = payApplyId;
                        payDetailEntity[i].ExpenseID = int.Parse(expenseGridView.GetRowCellValue(rowIds[i], "ExpenseID").ToString());
                        payDetailEntity[i].ApplyPay = decimal.Parse(expenseGridView.GetRowCellValue(rowIds[i], "ApplyPay").ToString());
                        payDetailEntity[i].PayStatus = PayDetailStatusEnum.未付.ToString();
                    }
                    #endregion

                    #region 打印付款申请单（报表）

                    PayApplyFormDataSet ds = new PayApplyFormDataSet();
                    if (sender.Equals(btnPrint))
                    {
                        //写入付款申请表和付款详情表
                        payApplyId = PayApplyCtrl.CreatePayApplyAndPayDetailData(payApplyEntity, payDetailEntity);
                    }
                    //if (sender.Equals(btnPrint))//是打印，从数据库中获取
                    //    foreach (DataRow dr in PayApplyCtrl.GetPayApplyDataById(payApplyId).Rows)
                    //        ds.Tables["fin_PayApply"].ImportRow(dr);
                    //else//是预览，从前面内容中获取
                    //{
                        DataTable dt = PayApplyCtrl.GetPayApplyDataById("-1");//传入‘-1’获取表结构
                        DataRow dr = dt.NewRow();
                        dr["PayApplyID"] = payApplyId;
                        dr["ProviderName"] = payApplyEntity.ProviderName;
                        dr["ProviderID"] = payApplyEntity.ProviderID;
                        //dr["Contact"] = payApplyEntity.Contact;
                        //dr["Telephone"] = payApplyEntity.Telephone;
                        //dr["Fax"] = payApplyEntity.Fax;
                        dr["TotalpaymentG"] = payApplyEntity.TotalpaymentG;
                        dr["TotalpaymentL"] = payApplyEntity.TotalpaymentL;
                        dr["Applicants"] = payApplyEntity.Applicants;
                        dr["Audit"] = payApplyEntity.Audit;
                        dr["PlanPayTime"] = payApplyEntity.PlanPayTime;
                        dr["ApplyPayTime"]  = payApplyEntity.ApplyPayTime;
                        dr["PayTime"] = payApplyEntity.PayTime;
                        dr["PayStatus"] = payApplyEntity.PayStatus;
                        dr["Remark"] = payApplyEntity.Remark;
                        dt.Rows.Add(dr);
                    //} 

                    //导入数据
                    ds.Tables["fin_PayApply"].ImportRow(dr);

                    ds.Tables["bas_Provider"].Rows.Add();
                    ds.Tables["bas_Provider"].Rows[0]["ProviderName"] = provider.ProviderName;
                    ds.Tables["bas_Provider"].Rows[0]["FullName"] = provider.FullName;
                    ds.Tables["bas_Provider"].Rows[0]["Contact"] = provider.Contact;
                    ds.Tables["bas_Provider"].Rows[0]["Telephone"] = provider.Telephone;
                    ds.Tables["bas_Provider"].Rows[0]["Fax"] = provider.fax;
                    ds.Tables["bas_Provider"].Rows[0]["AccountBank"] = provider.AccountBank;
                    ds.Tables["bas_Provider"].Rows[0]["Account"] = provider.Account;

                    foreach (int id in rowIds)
                    {
                        ds.Tables["fee_Expense"].ImportRow(expenseGridView.GetDataRow(id));

                        //设置费用支付状态为申请
                        ExpensesCtrl.UpdateExpensePayStatus(expenseGridView.GetRowCellValue(id, "ExpenseID").ToString(), PayApplyStatusEnum.申请);

                    }
                    PayApplyFormRpt rpt = new PayApplyFormRpt(payApplyEntity.ProviderID.ToString());
                    rpt.DataSource = ds;
                    if (sender.Equals(btnPrint))
                    {
                        
                        rpt.PrintDialog();
                    }
                    else
                        new PrintPreviewForm(rpt, "").ShowDialog();
                    #endregion

                    #region 写入付款详情数据
                    if (sender.Equals(btnPrint))
                    {

                        //更新费用详情(表中‘已申请总额’)
                        Dictionary<int, decimal> data = new Dictionary<int, decimal>();
                        Dictionary<int, string> tourGroupIds = new Dictionary<int, string>();

                        for (int i = 0; i < rowIds.Length; i++)
                        {
                            //DataRowView drv = BindingContext[_dtPayApply].Current as DataRowView;
                            decimal applyPay = expenseGridView.GetRowCellValue(rowIds[i], "ApplyPay").ToString() == "" ? 0 : decimal.Parse(expenseGridView.GetRowCellValue(rowIds[i], "ApplyPay").ToString());//drv["ApplyPay"] == null ? 0 : decimal.Parse(drv["ApplyPay"].ToString());//本次申请额
                            decimal applyPayTotal = expenseGridView.GetRowCellValue(rowIds[i], "ApplyPayTotal").ToString() == "" ? 0 : decimal.Parse(expenseGridView.GetRowCellValue(rowIds[i], "ApplyPayTotal").ToString()); //drv["ApplyPayTotal"] == null ? 0 : decimal.Parse(drv["ApplyPayTotal"].ToString());//已申请总额
                            int expenseId = int.Parse(expenseGridView.GetRowCellValue(rowIds[i], "ExpenseID").ToString());
                            string tourGroupId = expenseGridView.GetRowCellValue(rowIds[i], "TourgroupID").ToString();

                            expenseGridView.SetRowCellValue(rowIds[i], "ApplyPayTotal", applyPayTotal + applyPay);//drv["ApplyPayTotal"] = applyPayTotal + applyPay;//更新界面‘已申请总额’单元格
                            data.Add(expenseId, applyPayTotal + applyPay);

                            tourGroupIds.Add(expenseId, tourGroupId);

                            ExpensesCtrl.UpdateExpenseApplyPayTotal(expenseId);
                       }

                        //更新团实际成本
                        TeamGroupCtrl.UpdateTourGroupRealCostbyGourpIDs(tourGroupIds);

                    }
                    #endregion

                    //MessageBox.Show("打印完毕！", "结果信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }

        }
        /// <summary>
        /// 校验选择数据是否合法
        /// </summary>
        /// <param name="totalpayment">校验通过，返回本次申请额总和</param>
        /// <param name="providerID">校验通过，返回供应商ID</param>
        /// <param name="rowIds">返回所有选中的行号</param>
        /// <returns>校验是否通过</returns>
        private bool ValidateData(out decimal totalpayment, out string providerID, out int[] rowIds)
        {
            msg.Clear();

            //判断是否是同一供应商，以及本次申请费用和
            totalpayment = 0;
            providerID = "";

            //expenseGridView.ClearSelection();
            rowIds = MutilRow(expenseGridView);

            if (rowIds.Length >= 1)
            {
                providerID = expenseGridView.GetRowCellValue(rowIds[0], "ProviderID").ToString();

                totalpayment = decimal.Parse(expenseGridView.GetRowCellValue(rowIds[0], "ApplyPay").ToString());
                for (int i = 0; i < rowIds.Length; i++)
                {
                    if (providerID != expenseGridView.GetRowCellValue(rowIds[i], "ProviderID").ToString())
                    {
                        msg.AppendText("选中项的各个'供应商'不完全相同，请选择相同供应商项\r\n");
                        messageDockPanel.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Visible;
                        return false;
                    }
                    if (decimal.Parse(expenseGridView.GetRowCellValue(rowIds[i], "ApplyPay").ToString()) == 0)
                    {
                        msg.AppendText("选择项中有'本次申请额'为空项,请填写完整申请额\r\n");
                        messageDockPanel.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Visible;
                        return false;
                    }

                    if( expenseGridView.GetRowCellValue(rowIds[i], "PayStatus").ToString() == PayApplyStatusEnum.付清.ToString())
                    {
                        msg.AppendText("选择项中有费用'付清'状态，不允许申请\r\n");
                        messageDockPanel.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Visible;
                        return false;
                    }

                    if (expenseGridView.GetRowCellValue(rowIds[i], "Status").ToString() == ExpenseStatusEnum.终结.ToString())
                    {
                        msg.AppendText("选择项中有团'终结'状态，不允许申请\r\n");
                        messageDockPanel.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Visible;
                        return false;
                    }

                    //if (decimal.Parse(expenseGridView.GetRowCellValue(rowIds[i], "ApplyPayTotal").ToString()) + decimal.Parse(expenseGridView.GetRowCellValue(rowIds[i], "ApplyPay").ToString()) > decimal.Parse(expenseGridView.GetRowCellValue(rowIds[i], "Budget").ToString()))
                    //{
                    //    msg.AppendText("'本次申请额'与'已支付金额'之和大于'应付金额',请修改'本次申请额'或'应付金额'\r\n");
                    //    messageDockPanel.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Visible;
                    //    return false;
                    //}

                    if (i != 0)    //非第一行
                        totalpayment += decimal.Parse(expenseGridView.GetRowCellValue(rowIds[i], "ApplyPay").ToString());
                }

                //if (tbContact.Text == "")
                //{
                //    msg.AppendText("您还没有填写‘收款人姓名’，这是必须的哦！\r\n");
                //    messageDockPanel.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Visible;
                //    return false;
                //}
                return true;
            }
            msg.AppendText("没有选择任何内容，请在选择项上打‘√’\r\n");
            return false;
        }

        #endregion
        

        private void payApplyGridView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle < 0) return;

            string expenseId = expenseGridView.GetRowCellValue(e.FocusedRowHandle, "ExpenseID").ToString();
            //payDetailGridControl.DataSource = PayDetailCtrl.GetPayDetailDataByExpenseId(expenseId);
            DataTable payDt = PayDetailCtrl.GetPayDetailDataByExpenseId(expenseId);
            DataTable cashDt = CashDetailCtrl.GetCashDetailDataByExpenseID(expenseId);
            payDetailGridControl.DataSource = (payDt != null && payDt.Rows.Count > 0) ? payDt : cashDt;//谁不为空显示谁(付款详情和报销详情)
        }

        private void payApplyGridView_RowStyle(object sender, RowStyleEventArgs e)
        {
            if (e.RowHandle < 0) return;
            object selected = expenseGridView.GetRowCellValue(e.RowHandle, "Selected");

            if (string.IsNullOrEmpty(selected.ToString())) return;

            if (Convert.ToBoolean(selected) == true)
            {
                e.Appearance.BackColor = Color.Wheat;
                e.Appearance.BackColor2 = Color.Azure;
            }
            else
            {
                e.Appearance.BackColor = Color.Empty;
                e.Appearance.BackColor2 = Color.Empty;
            }
        }

        #region 多选处理

        private void expenseGridView_Click(object sender, EventArgs e)
        {
            if (DevGridCheckControl.ClickGridCheckBox(this.expenseGridView, "Selected", m_checkStatus))
            {
                m_checkStatus = !m_checkStatus;
            }
        }

        private void expenseGridView_CustomDrawColumnHeader(object sender, ColumnHeaderCustomDrawEventArgs e)
        {
            if (e.Column != null && e.Column.FieldName == "Selected")
            {
                e.Info.InnerElements.Clear();
                e.Painter.DrawObject(e.Info);
                DevGridCheckControl.DrawCheckBox(e, m_checkStatus);
                e.Handled = true;
            }
        } 

        #endregion


    }
}
